﻿using EasyXaf.EntityDesigner.BusinessObjects.Enums;
using System.Text.RegularExpressions;

namespace EasyXaf.EntityDesigner.Commands;

public class CreateEnumCommand : ICommand
{
    private static Enumeration CreateEnum(string command, CommandContext context)
    {
        var originalCommand = command;

        command = command[1..];

        if (command.Contains('('))
        {
            command = command[..command.IndexOf('(')];
        }

        var matches = Regex.Matches(command, @"(?<=\s|^).*?(?=\s|$)").Cast<Match>();

        var enumName = matches.FirstOrDefault()?.Value;
        if (string.IsNullOrWhiteSpace(enumName))
        {
            throw new CommandException(originalCommand, "枚举名称不能为空");
        }

        var enumeration = context.DomainModel.Enums.FirstOrDefault(e => e.Name == enumName);
        if (enumeration != null)
        {
            throw new CommandException(originalCommand, $"枚举 '{enumName}' 已存在");
        }

        enumeration = context.ObjectSpace.CreateObject<Enumeration>();
        enumeration.Name = enumName;
        enumeration.Caption = matches.Skip(1).FirstOrDefault()?.Value;
        enumeration.DomainModel = context.DomainModel;

        return enumeration;
    }

    private static void CreateEnumValues(string command, Enumeration enumeration, CommandContext context)
    {
        var enumValuesParams = Regex.Match(command[1..], @"(?<=\().*?(?=\))").Value?.Trim()?.Split(',');
        if (enumValuesParams == null || enumValuesParams.Length == 0)
        {
            return;
        }

        foreach (var enumValueParams in enumValuesParams)
        {
            if (string.IsNullOrWhiteSpace(enumValueParams))
            {
                continue;
            }

            var matches = Regex.Matches(enumValueParams.Trim(), @"(?<=\s|^).*?(?=\s|$)").Cast<Match>();

            var enumValueName = matches.FirstOrDefault()?.Value;
            if (string.IsNullOrWhiteSpace(enumValueName))
            {
                throw new CommandException(command, "枚举值名称不能为空");
            }

            var enumValue = enumeration.Values.FirstOrDefault(x => x.Name == enumValueName);
            if (enumValue != null)
            {
                throw new CommandException(command, $"枚举值 '{enumValueName}' 已存在");
            }

            enumValue = context.ObjectSpace.CreateObject<EnumValue>();
            enumValue.Name = enumValueName;
            enumValue.Caption = matches.Skip(1).FirstOrDefault()?.Value;
            enumValue.Enum = enumeration;
        }
    }

    public bool CanExecute(string command)
    {
        return command.StartsWith('*');
    }

    public void Execute(string command, CommandContext context)
    {
        var enumeration = CreateEnum(command, context);
        CreateEnumValues(command, enumeration, context);
    }
}
